package org.catpay.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.catpay.modules.sys.dao.SysRoleMenuDao;
import org.catpay.modules.sys.entity.SysRoleMenuEntity;
import org.catpay.modules.sys.service.SysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * 角色与菜单对应关系
 * 
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenuEntity>
		implements SysRoleMenuService {

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
		
			// 先删除角色与菜单关系
			deleteBatch(new Long[] { roleId });

			if (menuIdList.size() == 0) {
				return;
			}

			// 保存角色与菜单关系
			List<SysRoleMenuEntity> list = new ArrayList<>(menuIdList.size());
			for (Long menuId : menuIdList) {
				SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
				sysRoleMenuEntity.setMenuId(menuId);
				sysRoleMenuEntity.setRoleId(roleId);
				list.add(sysRoleMenuEntity);
			}
			this.insertBatch(list);
	
	}

	@Override
	public List<Long> queryMenuIdList(Long roleId) {
		List<SysRoleMenuEntity> l = new SysRoleMenuEntity()
				.selectList(new EntityWrapper<>().setSqlSelect("menu_id").eq("role_id", roleId));
		List<Long> result = new ArrayList<>();
		l.forEach(srm -> {
			result.add(srm.getMenuId());
		});
		return result;
	}

	@Override
	public boolean deleteBatch(Long[] roleIds) {
		return new SysRoleMenuEntity().delete(new EntityWrapper<>().in("role_id", roleIds));
	}

}
